package com.wishwingz.klipper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;

import com.actionbarsherlock.app.SherlockActivity;
import com.wishwingz.klipper.cache.CacheType;

public class SplashActivity extends SherlockActivity {
	static final String METHOD_POST = "POST";
	private BufferedReader request;
	private String returnJson;
	private File cacheFile;
	private Handler mHandler;

	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash);
		//캐쉬파일 초기 세팅
		cacheFile = new File(this.getCacheDir().getAbsolutePath(),
				CacheType.PRODUCT_MODEL.getFileName());
		
		//Splash 이미지 및 백그라운 task용 핸들러
		mHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					finish();
				} else if (msg.what == 1) {
					Log.d("Background Task", "백그라운드 작업 완료");
				}
			}
		};
		//백그라운 task 시작 
		doBackGroundSubmit();
		mHandler.sendEmptyMessageDelayed(0, 2000);
	}

	private void doBackGroundSubmit() {
		Thread thread = new Thread(null, doBackgroundThreadProcessing,
				"Background");
		thread.start();
	}

	private Runnable doBackgroundThreadProcessing = new Runnable() {
		@Override
		public void run() {
			backgroundThreadProcessing();
		}
	};
	//모델 정보를 캐쉬파일로 저장하기 위한 백그라운드 task
	private void backgroundThreadProcessing() {
		StringBuilder sb = new StringBuilder();
		try {
			Log.d("Background Task", "백그라운 시작");
			URL url = new URL("http://1.234.7.150:5007/sub_category");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(METHOD_POST);
			conn.setUseCaches(false);
			request = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String tag = "";

			while ((tag = request.readLine()) != null) {
				sb.append(tag);
			}

			returnJson = sb.toString();

			FileWriter fw = null;

			try {
				fw = new FileWriter(cacheFile);
				fw.write(returnJson);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				Log.d("Background Task", "백그라운 완료");
				if (fw != null) {
					try {
						fw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			mHandler.sendEmptyMessage(1);

		} catch (Exception e) {
			// 실패
			e.printStackTrace();
		} finally {
			ConnectionCloseManager.closeInputOutput(null, request);
		}
	}
}